import os

import FileOps
from Logger import *


def get_bytes_hex(filepath: str, start: str, stop: str):
    if not os.path.isfile(filepath):
        return None
    if int(start, base=16) > int(stop, base=16):
        return None
    bin_bytes = FileOps.read(filepath, "rb")
    if not bin_bytes:
        return None
    return bin_bytes[start: stop]


def get_bytes_dec(filepath: str, start: int, stop: int):
    if not os.path.isfile(filepath):
        return None
    if start > stop:
        return None
    bin_bytes = FileOps.read(filepath, "rb")
    if not bin_bytes:
        return None
    return bin_bytes[start: stop]

def set_bytes_hex(new_data: bytes, filepath_old: str, filepath_new: str, start: str, stop: str):
    if not os.path.isfile(filepath_old):
        return None
    if not new_data or not start or not stop or not filepath_new:
        return None
    start_dec = int(start, base=16)
    stop_dec = int(stop, base=16)
    if start_dec > stop_dec:
        return None
    if len(new_data) != stop_dec - start_dec:
        return None
    if not isinstance(new_data, bytes):
        return None

    bin_bytes = FileOps.read(filepath_old, "rb")
    if not bin_bytes:
        return None
    bin_bytes_new = bin_bytes[:start_dec] + new_data + bin_bytes[stop_dec:]
    result = FileOps.write(filepath_new, "wb", bin_bytes_new)
    if not result:
        return None
    return bin_bytes_new

def set_bytes_dec(new_data: bytes, filepath_old: str, filepath_new: str, start: str, stop: str):
    if not os.path.isfile(filepath_old):
        return None
    if (not new_data) or (not start) or (not stop) or (not filepath_new):
        return None
    if start > stop:
        return None
    if len(new_data) != stop - start:
        return None
    if not isinstance(new_data, bytes):
        return None

    bin_bytes = FileOps.read(filepath_old, "rb")
    if not bin_bytes:
        return None
    bin_bytes_new = bin_bytes[:start] + new_data + bin_bytes[stop:]
    result = FileOps.write(filepath_new, "wb", bin_bytes_new)
    if not result:
        return None
    return bin_bytes_new